﻿using System;
using System.Threading;
using System.Windows.Forms;
using S7PlcDataManager.Tools;

namespace S7PlcDataManager
{
    static class Program
    {
        private static Mutex _instanceMutex;

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            LogHelper.InitLogPath();
            LogHelper.AddLog("Instance is starting.");

            Application.ApplicationExit += (sender, e) =>
            {
                _instanceMutex?.ReleaseMutex();
                _instanceMutex = null;
                LogHelper.AddLog("Instance is shutting down.");
                LogHelper.Stop();
            };

            //单实例检测
            if (!CheckSingleInstance())
            {
                LogHelper.AddErrorLog("Another instance is running!");
                Thread.Sleep(1);
                Application.Exit();
                return;
            }

            //异常捕获
            AddThreadExceptionHandler();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new FormMain());
        }

        /// <summary>
        /// 单实例检测
        /// </summary>
        private static bool CheckSingleInstance()
        {
            bool mutexWasCreated;
            _instanceMutex = new Mutex(true, "S7PlcDataManager", out mutexWasCreated);
            if (!mutexWasCreated)
            {
                _instanceMutex = null;
            }

            return mutexWasCreated;
        }

        /// <summary>
        /// 异常捕获
        /// </summary>
        private static void AddThreadExceptionHandler()
        {
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

            Application.ThreadException += (sender, args) => { LogHelper.AddLog($"未处理的线程异常：{args.Exception}"); };

            AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
            {
                LogHelper.AddLog($"未处理的UI异常：{(Exception)args.ExceptionObject}");
            };
        }
    }
}
